//
//  NewGuidManager.m
//  NewFeatureGuid
//
//  Created by gome on 2018/12/12.
//  Copyright © 2018 gome. All rights reserved.
//

#import "NewGuidManager.h"
#import "NewFeatureView.h"
#import "AppDelegate.h"

@interface NewGuidManager ()
@property (nonatomic, strong) NewFeatureView *maskView;
@end

@implementation NewGuidManager

/**
 新特新单例

 @return newGuidManager实例
 */
+ (instancetype) sharedInstence {
    static NewGuidManager *st__newGuidManager = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        st__newGuidManager = [[NewGuidManager alloc] init];
    });
    
    return st__newGuidManager;
}


/**
 蒙版层

 @return 返回蒙版层view
 */
- (NewFeatureView *)maskView {
    if (!_maskView) {
        _maskView = [[NewFeatureView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
        [_maskView setBackgroundColor:[[UIColor blackColor] colorWithAlphaComponent:0.7f]];
    }
    
    return _maskView;
}


/**
 展示多个tips

 @param tipsArray tips 相关数组
 */
- (void)showWithTipsArray:(NSArray <NSDictionary *>*)tipsArray {
    [self showWithTipsArray:tipsArray compelete:^{
        [self.maskView removeFromSuperview];
        self.maskView = nil;
        NSLog(@"结束");
    }];
}


/**
 带回调的展示多个tips

 @param tipsArray tips 相关数组
 @param compelete 展示结束的回调
 */
- (void)showWithTipsArray:(NSArray <NSDictionary *>*)tipsArray compelete:(void (^)(void))compelete {
    [self.maskView setWithArray:tipsArray compelete:compelete];
    UIWindow *mainWindow = (UIWindow *)[[UIApplication sharedApplication] delegate].window;
    [mainWindow addSubview:_maskView];
}

/**
 获取view相对于根view（ctrl.view）的frame
 
 @param view b目标view
 @return 相对于根view的frame
 */
+ (CGRect)convertRectFromWindow:(UIView *)view {
    if (!view) {
        return CGRectZero;
    }
    
    NSMutableArray *superViews = [NSMutableArray array];
    
    UIView *sview = view.superview;
    
    while (sview) {
        [superViews addObject:sview];
        sview = sview.superview;
    }
    
    
    CGRect tfRect = view.frame;
    
    if (superViews.count == 1) {
        return tfRect;
    }
    
    for (int i = 0; i < superViews.count - 1; i++) {
        
        UIView *targetFatherView = superViews[i+0];
        UIView *targetFatherSuperview = superViews[i+1];
        
        tfRect = [targetFatherView convertRect:tfRect toView:targetFatherSuperview];
    }
    
    return tfRect;
}
@end
